<template>
  <div style="padding: 20px;">
    <el-descriptions title="班级信息" border>
      <el-descriptions-item label="班级编号">{{ classInfo.classCode }}</el-descriptions-item>
      <el-descriptions-item label="班级名称">{{ classInfo.name }}</el-descriptions-item>
      <el-descriptions-item label="人数分布"> 男：{{ classInfo.boyNum }}  || 女：{{ classInfo.girlNum }}</el-descriptions-item>
      <el-descriptions-item label="班级性质">
        <el-tag size="small">{{ classInfo.type }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="班级简介">{{ classInfo.desc }}</el-descriptions-item>
    </el-descriptions>
    <!-- 操作 -->
    <el-row style="margin: 5px 0 5px 0">
      <!-- 搜索学生 -->
      <el-col :span="22">
        <el-input v-model="keyword" placeholder="搜索姓名或者学号" class="input-with-select" @keyup.enter.native="keywordSearchHandler()">
          <el-button slot="append" icon="el-icon-search" @click="keywordSearchHandler()" @keyup.enter.native="keywordSearchHandler()" />
        </el-input>
      </el-col>
      <!-- 添加学生 btn -->
      <el-col :span="2" style="text-align: right;">
        <el-button type="primary" @click="openAdd()">添加学生</el-button>
      </el-col>
    </el-row>
    <!-- 班级学生列表 -->
    <el-table v-loading="listLoading" :data="students.data" border style="width: 100%">
      <el-table-column align="center" prop="studentNumber" label="学号" width="130" />
      <el-table-column align="center" prop="nickname" label="姓名" width="180" />
      <el-table-column align="center" prop="age" label="年龄" width="80" />
      <el-table-column align="center" prop="sex" label="性别" width="80" />
      <el-table-column align="center" prop="idCard" label="身份证" />
      <el-table-column align="center" prop="origin" label="籍贯" />
      <el-table-column align="center" prop="address" label="居住地址" />
      <el-table-column align="center" prop="concat" label="联系电话" />
      <el-table-column align="center" prop="familyConcat" label="家庭联系电话" />
      <el-table-column align="center" prop="rating" label="评价" />
      <el-table-column align="center" fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editStudentHandler(scope.row)">查看/编辑</el-button>
          <el-button type="text" size="small" @click="delStudentHandler(scope.row)">删除</el-button>
          <el-button type="text" size="small" @click="shiftStudentHandler(scope.row)">调班</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px; text-align: right;"
      background
      layout="prev, pager, next"
      :current-page="pagination.page"
      :page-size.sync="pagination.limit"
      :page-count="students.totalPage"
      :hide-on-single-page="students.total <= students.limit"
      @current-change="pageHandler"
    />
    <!-- 添加学生框 -->
    <el-dialog :style="operaMode === 2 ? 'text-align: center;':'' " :title="operaTitle" :visible.sync="operaStudentShow">
      <el-form v-if="operaMode === 0 || operaMode === 1" :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.nickname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证" :label-width="formLabelWidth">
          <el-input v-model="form.idCard" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系方式" :label-width="formLabelWidth">
          <el-input v-model="form.concat" autocomplete="off" />
        </el-form-item>
        <el-form-item label="家庭联系方式" :label-width="formLabelWidth">
          <el-input v-model="form.familyConcat" autocomplete="off" />
        </el-form-item>
        <el-form-item label="籍贯" :label-width="formLabelWidth">
          <el-input v-model="form.origin" autocomplete="off" />
        </el-form-item>
        <el-form-item label="居住地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="operaMode === 1" label="评价" :label-width="formLabelWidth">
          <el-input v-model="form.rating" min-height="120" type="textarea" autocomplete="off" />
        </el-form-item>
      </el-form>
      <el-select v-if="operaMode === 2" v-model="shiftClassId" filterable placeholder="请选择" style="width:50%; text-align: center;">
        <el-option
          v-for="item in directorClassList"
          :key="item.id"
          :label="`${item.name}: ${item.size} 人`"
          :value="item.id"
        />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="operaStudentShow = false">取 消</el-button>
        <el-button type="primary" @click="operaStudentHandler(operaMode)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { studentList, addStudent, editStudent, delStudent } from '@/api/class_student'
import { info, staticsDirectorClass } from '@/api/class'
import { Message } from 'element-ui'
export default {
  name: 'ClassDetail',
  data() {
    return {
      // 操作学生的状态：0 是新增， 1 是修改，2 是进行班级调整
      operaMode: 0,
      operaTitle: '添加学生',
      // 当前班级的 id
      id: 0,
      // 学生列表是否加载
      listLoading: false,
      // 学生列表
      students: [],
      // 学生信息框是否显示
      operaStudentShow: false,
      // 搜索
      keyword: '',
      // 学生信息表单
      form: {
        studentId: 0,
        classId: this.id,
        nickname: '',
        idCard: '',
        concat: '',
        familyConcat: '',
        origin: '',
        address: '',
        sex: '',
        rating: ''
      },
      // 表单的 label 宽度
      formLabelWidth: '120px',
      // 分页数据
      pagination: {
        page: 0,
        limit: 10
      },
      // 班级信息
      classInfo: {},
      // 负责的班级
      directorClassList: [],
      shiftClassId: null
    }
  },
  watch: {
    operaMode(n, o) {
      if (n === 0) {
        this.operaTitle = '添加学生'
      } else if (n === 1) {
        this.operaTitle = '查看/修改学生信息'
      } else if (n === 2) {
        this.operaTitle = '学生班级调整'
      }
    },
    keyword(n) {
      // 如果 keyword 被清空，则重新发送列表查询请求
      if (!n || (n && n.trim() === '')) {
        this.pagination.page = 0
        this.getStudentList()
      }
    }
  },
  mounted() {
    this.id = this.$route.params.id
    if (!this.id) {
      Message({
        message: '获取班级信息失败，请重试',
        type: 'error',
        duration: 5 * 1000
      })
      // 返回主页
      this.$router.push(
        {
          name: 'Dashboard'
        }
      )
      return
    }
    this.getClassInfo()
    this.getStudentList()
  },
  methods: {
    /**
     * 获取班级信息
     */
    getClassInfo() {
      info(this.id).then(res => {
        this.classInfo = res.data
      })
    },
    /**
     * 获取学生列表
     */
    getStudentList() {
      this.listLoading = true
      const data = {
        id: this.id,
        page: this.pagination.page,
        limit: this.pagination.limit
      }
      // 校验追加搜索关键字
      if (this.keyword && this.keyword.trim() !== '') {
        data.keyword = this.keyword
      }
      studentList(data).then(res => {
        this.students = res.data
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 打开新增用户操作框
     */
    openAdd() {
      this.operaMode = 0
      // 初始化表单
      this.form = {
        studentId: 0,
        classId: this.id,
        nickname: '',
        idCard: '',
        concat: '',
        familyConcat: '',
        origin: '',
        address: '',
        sex: ''
      }
      this.operaStudentShow = true
    },
    /**
     * 操作学生信息
     */
    operaStudentHandler() {
      this.form.classId = this.id
      if (this.operaMode === 0) {
        // 新增，删除 classId
        addStudent(this.form).then(res => {
          Message({
            message: '新增成功学号为：' + res.data,
            type: 'success',
            duration: 5 * 1000
          })
          // 重新获取列表
          this.getStudentList()
        }).finally(() => {
          this.operaStudentShow = false
        })
      } else if (this.operaMode === 1) {
        // 修改
        editStudent(this.form).then(() => {
          Message({
            message: '修改信息成功',
            type: 'success',
            duration: 5 * 1000
          })
          // 重新获取列表
          this.getStudentList()
        }).finally(() => {
          this.operaStudentShow = false
        })
      } else if (this.operaMode === 2) {
        editStudent({ classId: this.shiftClassId, studentId: this.form.studentId }).then(() => {
          Message({
            message: '调班成功',
            type: 'success',
            duration: 5 * 1000
          })
          // 重新获取列表
          this.getStudentList()
        }).finally(() => {
          this.operaStudentShow = false
        })
      }
    },
    /**
     * 修改学生信息
     * @param {表格行信息} row
     */
    editStudentHandler(row) {
      this.operaMode = 1
      this.form = { ...row }
      if (row.sex === '男') {
        this.form.sex = '1'
      } else if (row.sex === '女') {
        this.form.sex = '0'
      }
      this.form.studentId = row.userId
      this.operaStudentShow = true
    },
    /**
     * 删除学生信息
     * @param {表格行信息} row
     */
    delStudentHandler(row) {
      delStudent(row.userId).then(() => {
        Message({
          message: '删除成功',
          type: 'success',
          duration: 5 * 1000
        })
      }).finally(() => {
        this.getStudentList()
      })
    },
    /**
     * 页面改变操作
     * @param {当前页} val
     */
    pageHandler(val) {
      if (val > 0) {
        this.pagination.page = val
      }
      this.getStudentList()
    },
    /**
     * 调班
     * FIXME:当前仅支持调至自己所负责的班级
     * @param {表格行信息} row
     */
    shiftStudentHandler(row) {
      this.operaMode = 2
      this.operaStudentShow = true
      // 获取负责的班级
      staticsDirectorClass().then(res => {
        this.directorClassList = res.data
        // 排除当前班级
        this.directorClassList = this.directorClassList.filter(dc => dc.id !== this.id)
        console.log('this.directorClassList = ', this.directorClassList)
        this.form.studentId = row.userId
      })
    },
    /**
     * 关键字搜索
     */
    keywordSearchHandler() {
      // 初始化分页
      this.pagination.page = 0
      this.getStudentList()
    }
  }
}

</script>

<style lang="scss" scoped>

</style>
